package com.galen.manual.config;

import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Minio配置类
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

    /**
     * Minio服务地址
     */
    private String endpoint = "http://localhost:9000";

    /**
     * Minio访问用户名
     */
    private String accessKey = "minioadmin";

    /**
     * Minio访问密钥
     */
    private String secretKey = "minioadmin";

    /**
     * Minio存储桶名称
     */
    private String bucketName = "manual";

    /**
     * 自定义域名（可选）
     */
    private String customDomain;

    /**
     * 是否启用HTTPS
     */
    private boolean secure = false;

    /**
     * 地区
     */
    private String region = "us-east-1";

    /**
     * 创建Minio客户端
     */
    @Bean
    public MinioClient minioClient() {
        try {
            log.info("正在初始化Minio客户端，端点: {}", endpoint);

            MinioClient client = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .region(region)
                    .build();

            log.info("Minio客户端初始化成功");
            return client;
        } catch (Exception e) {
            log.error("Minio客户端初始化失败", e);
            throw new RuntimeException("Minio客户端初始化失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取文件访问URL
     */
    public String getFileUrl(String objectName) {
        if (customDomain != null && !customDomain.trim().isEmpty()) {
            return customDomain + "/" + bucketName + "/" + objectName;
        }
        return endpoint + "/" + bucketName + "/" + objectName;
    }
}